<template>
  <a-modal
    title="登录"
    :visible="visible"
    :confirm-loading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    ok-text="登录"
    cancel-text="注册"
    class="login-modal"
  >
    <a-form ref="ruleForm" :form="form" class="login-input">
      <a-form-item label="">
        <a-input
          :maxLength="maxLen"
          placeholder="手机号"
          hasFeedback
          v-decorator="[
            'account',
            {
              rules: [
                {
                  required: true,
                  message: '请输入11位手机号'
                }
              ]
            }
          ]"
        />
      </a-form-item>
      <a-form-item label="">
        <a-input-password
          placeholder="密码"
          hasFeedback
          v-decorator="[
            'passwd',
            { rules: [{ required: true, message: '请输入登录密码', min: 3 }] }
          ]"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { MD5 } from "crypto-js";
export default {
  name: "Login",
  data() {
    return {
      maxLen: 11,
      visible: false,
      confirmLoading: false,
      form: this.$form.createForm(this, { name: "dynamic_rule" })
    };
  },
  watch: {
    "$store.state.login.modalVisible": {
      handler(nval) {
        this.visible = nval;
      }
    }
  },
  methods: {
    setVisible() {
      this.$store.commit("login/setModalVisible", { val: !this.visible });
    },
    async handleOk() {
      const { $axios, form } = this;
      this.confirmLoading = true;
      const account = form.getFieldValue("account");
      const passwd = form.getFieldValue("passwd");
      const res = await $axios.post("/user/login", {
        account,
        passwd: MD5(passwd).toString()
      });
      const { status, token, id } = res.data;
      if (status == 0) {
        sessionStorage.setItem(
          "user",
          JSON.stringify({
            account: res.data.account,
            token: res.data.token,
            id: res.data.id
          })
        );
        this.$store.commit("login/setUser", { val: { id } });
        this.setVisible();
        this.$message.success("登录成功");
      } else {
        this.$message.error("登录失败");
      }
      this.confirmLoading = false;
    },
    handleCancel() {
      this.setVisible();
    }
  }
};
</script>
<style lang="less" scoped>
.login-modal {
  .login-input {
    width: 60%;
    margin: auto;
  }
}
</style>
